﻿using System.IO;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;
using System.Xml;
using OWASP.CodeReview.CodeCrawler.Functionalities.Emails.ExceptionsHandling;

namespace CodeCrawler.UI.Functionalities.Emails {
    /// <summary>
    /// Send Reports by Email using System.NET.Mail
    /// Features: External Configuration Settings
    /// </summary>
    internal class EmailCore {
        private readonly string EmailSettingsFilePath = string.Concat(Application.StartupPath,
                                                                      "/Functionalities/Emails/Settings/EmailSettings.xml");
        public int serverport { get; set; }
        public string smtpserver { get; set; }
        public string useremailaddress { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string title { get; set; }
        public string body { get; set; }
        public bool isMessageHighPriorityByDefault { get; set; }
        public bool isSecureSSL { get; set; }


        /// <summary>
        /// Send a Code Crawler Generated Report By Email for further
        /// clarifications
        /// </summary>
        /// <param name="sername"></param>
        /// <param name="password"></param>
        public int Send(string receipt, string body, bool IsUrgent, string reportName) {
            ReadUserProfile();

            var _mailMessage = new MailMessage();
            _mailMessage.From = new MailAddress(useremailaddress);
            _mailMessage.To.Add(receipt);
            _mailMessage.Subject = "OWASP Code Crawler - Code Review Result Attached";
            _mailMessage.Body = body;
            _mailMessage.IsBodyHtml = true;

            if (isMessageHighPriorityByDefault) {
                _mailMessage.Priority = MailPriority.High;
            }
            else {
                if (IsUrgent) {
                    _mailMessage.Priority = MailPriority.High;
                }
                else {
                    _mailMessage.Priority = MailPriority.Normal;
                }
            }

            if (!string.IsNullOrEmpty(GetAttachmentFullFilePath(reportName))) {
                var attachedReport = new Attachment(GetAttachmentFullFilePath(reportName));
                _mailMessage.Attachments.Add(attachedReport);

                var sC = new SmtpClient(smtpserver);
                sC.Port = serverport;
                sC.Credentials = new NetworkCredential(username, password);
                sC.EnableSsl = isSecureSSL;
                sC.Send(_mailMessage);
                return 1;
            }
            // ErrorID : -2
            // Description = No report attached
            // Aborting
            throw new EmailExceptions.NoReportAttached();
        }

        #region Helper Methods

        #region System.IO
        /// <summary>
        /// Given a Report Name returns its full path
        /// </summary>
        /// <param name="reportName">Report Name</param>
        /// <returns>Report Full IO path</returns>
        private string GetAttachmentFullFilePath(string reportName) {
            var _reportsFolder = new DirectoryInfo(string.Concat(Application.StartupPath, "/Reports"));
            string returnValue = string.Empty;

            foreach (FileInfo _file in _reportsFolder.GetFiles("*.xml")) {
                if (_file.Name.ToLower().Equals(reportName.ToLower())) {
                    returnValue = _file.FullName;
                    break;
                }
                else {
                    break;
                }
            }

            return returnValue;
        }
        #endregion

        #region User Specific Settings
        /// <summary>
        /// Read the content of the /Functionalities/Emails/Settings/EmailSettings.xml file
        /// </summary>
        public void ReadUserProfile() {
            var _settingsReader = new XmlTextReader(EmailSettingsFilePath);
            while (_settingsReader.Read()) {
                XmlNodeType _nodeType = _settingsReader.NodeType;
                if (_nodeType == XmlNodeType.Element) {
                    switch (_settingsReader.Name.ToLower()) {
                            #region Read And Set Variables
                        case "smtpserver": {
                            smtpserver = _settingsReader.ReadElementContentAsString();
                            break;
                        }

                        case "useremail": {
                            useremailaddress = _settingsReader.ReadElementContentAsString();
                            break;
                        }

                        case "smtpusername": {
                            username = _settingsReader.ReadElementContentAsString();
                            break;
                        }

                        case "smtppassword": {
                            password = _settingsReader.ReadElementContentAsString();
                            break;
                        }

                        case "securessl": {
                            isSecureSSL = _settingsReader.ReadElementContentAsBoolean();
                            break;
                        }

                        case "highprioritybydefault": {
                            isMessageHighPriorityByDefault = _settingsReader.ReadElementContentAsBoolean();
                            break;
                        }

                        case "serverport": {
                            serverport = _settingsReader.ReadElementContentAsInt();
                            break;
                        }
                            #endregion
                    }
                }
            }
        }
        #endregion

        #endregion
    }
}